# encoding: utf-8
class Api::MonitoringFilesController < ApplicationController
  respond_to :json
  
  skip_before_filter :verify_authenticity_token 
  
  before_action :set_monitoring_file, only: [:show, :edit, :update, :destroy]

  # GET /api/monitoring_files
  def index
    project = Project.where("name = ?", params[:project_name]).first
    unless project.nil?
      @monitoring_files = MonitoringFile.includes(:user).where("project_id = ?", project.id).all
      render json: @monitoring_files, :include => {:user => {:only => :email} }, :except => [:created_at, :updated_at]
    else 
      render json: {"error" => true, "message" => "invalid project name provided"}.to_json, status: :unprocessable_entity
    end 
  end

  # GET /api/monitoring_files/1
  def show
    respond_with @monitoring_file
  end

  # GET /api/monitoring_files/new
  def new
    @monitoring_file = MonitoringFile.new
  end

  # GET /api/monitoring_files/1/edit
  def edit
  end

  # POST /api/monitoring_files
  def create
    @user = User.where(:email => params[:user_email]).first
    @project = Project.where(:name => params[:project_name]).first
    
    if @user.nil? or @project.nil?
       respond_to do |format|
          format.json { render json: {"error" => true, "message" => "invalid user or project name provided"}.to_json, status: :unprocessable_entity }  
       end  
    else 
      @monitoring_file = MonitoringFile.new
      @monitoring_file.user_id = @user.id
      @monitoring_file.project_id = @project.id
      @monitoring_file.name = params[:monitoring_file][:name]
      # path will be generated 
      #@monitoring_file.path = params[:monitoring_file][:path]
      file_path = "projects/%d/users/%d/%s" % [@project.id, @user.id, params[:monitoring_file][:name]]
      @monitoring_file.path = file_path
      
      respond_to do |format|
        if @monitoring_file.save
          format.json { render json: @monitoring_file }
        else
          format.json { render json: @monitoring_file.errors, status: :unprocessable_entity }
        end
      end
    end
  end

  # PATCH/PUT /api/monitoring_files/1
  def update
    respond_to do |format|
      if @monitoring_file.update(monitoring_file_params)
        format.json { head :no_content }
      else
        format.json { render json: @monitoring_file.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /api/monitoring_files/1
  def destroy
    @monitoring_file.destroy
    respond_to do |format|
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_monitoring_file
      @monitoring_file = MonitoringFile.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def monitoring_file_params
      params.require(:monitoring_file).permit(:user_email, :project_name, :name, :path)
    end
end
